package com.ljc;

/**
 * @author clj
 * @date 2022/8/29
 * @desc
 * Given a string s consisting of words and spaces, return the length of the last word in the string.
 * A word is a maximal substring consisting of non-space characters only.
 *
 * Example 1:
 * Input: s = "Hello World"
 * Output: 5
 * Explanation: The last word is "World" with length 5.
 *
 * Example 2:
 * Input: s = "   fly me   to   the moon  "
 * Output: 4
 * Explanation: The last word is "moon" with length 4.
 *
 * Example 3:
 * Input: s = "luffy is still joyboy"
 * Output: 6
 * Explanation: The last word is "joyboy" with length 6.
 */
public class E58LengthOfLastWord {
//    static String input = "   fly me   to   the moon  ";
//    static String input = "luffy is still joyboy";
    static String input = "Hello World";

    public static void main(String[] args) {
        int r = lengthOfLastWord(input);
        System.out.println(r);
    }

    public static int lengthOfLastWord(String input) {
        int point = input.length();
        System.out.println("input.length(): " + point);
        int r = 0;
        char space = ' ';
        for (int i = point-1; i >= 0; i--) {
            if (space != input.charAt(i) && space != input.charAt(i-1)) {
                r = r + 1;
            }else if (space != input.charAt(i) && space == input.charAt(i-1)) {
                r = r + 1;
                break;
            }
        }
        return r;
    }
}
